package jmine.tec.hydra.diagnostician;

import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import jmine.tec.hydra.HydraController;
import jmine.tec.hydra.domain.senderRegistry.MQSenderRegistry;

import org.springframework.beans.BeansException;

import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;
import bancosys.tec.rtm.impl.diagnostician.AbstractJNDIDiagnostician;

/**
 * Inspeciona o JNDI
 * 
 * @author jrenaut
 */
public class SenderRegistryJNDIDiagnostician extends AbstractJNDIDiagnostician {

    private HydraController controller;

    /**
     * C'tor
     * 
     * @param controller controller
     */
    public SenderRegistryJNDIDiagnostician(HydraController controller) {
        this.controller = controller;
    }

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return "Contexto JNDI";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean fillDiagnosisBean(DiagnosisBean bean) throws Exception {
        BaseDAO<MQSenderRegistry> dao = this.controller.getDAOFactory().getGenericDAO(MQSenderRegistry.class);

        Context ctx = this.getContext(bean);

        List<MQSenderRegistry> all = dao.findAll();
        bean.addDescription("Found " + all.size() + " MQSender(s)");
        for (MQSenderRegistry sender : all) {
            bean.addDescription("Checking JNDI lookups for MQSender " + sender.getMnemonico());
            bean.addDescription("    Checking QueueConnectionFactory lookup");
            this.lookup(ctx, sender.getQueueConnectionFactory(), bean);
            bean.addDescription("    Checking Queue lookup");
            this.lookup(ctx, sender.getQueue(), bean);
        }
        return true;

    }

    /**
     * @param bean o bean
     * @return o contexto JNDI
     * @throws NamingException ex
     */
    private Context getContext(DiagnosisBean bean) throws NamingException {
        Context ctx;
        try {
            ctx = this.controller.getJmsSenderContext();
            bean.addDescription("Using configured context.");
        } catch (BeansException e) {
            ctx = new InitialContext();
            bean.addDescription("Context not found. Creating a new one.");
        }
        return ctx;
    }
}
